//
//  KBOAuthViewController.swift
//  KimboWeiBoSwift
//
//  Created by kimbo on 15/12/18.
//  Copyright © 2015年 kimbo. All rights reserved.
//

import UIKit
import SVProgressHUD

class KBOAuthViewController: UIViewController {

    override func loadView() {
        view = webView
        webView.delegate = self //监听webView网络请求
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //发出登陆界面网络请求
        let url = KBNetWorkTool.sharedInstance.oAuthURL()
        webView.loadRequest(NSURLRequest(URL: url))
        
        //设置导航栏
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancle")
        
        navigationItem.title = "登陆"
    }
    
    // 自动填充帐号密码
    @objc private func autoFill() {
        // 创建js代码
        let js = "document.getElementById('userId').value='1187949260@qq.com'; document.getElementById('passwd').value='fty1187949260';"
        
        // 让webView来执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    // 取消
    @objc private func cancle() {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: 懒加载
    private lazy var webView: UIWebView = UIWebView()
    
}




// MARK: - 扩展,遵守UIWebViewDelegate协议
extension KBOAuthViewController: UIWebViewDelegate {
    
    /// webView开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载中...", maskType: SVProgressHUDMaskType.Black)
    }
    
    /// webView加载完毕
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    /// webView是否去加载一个网址,true就取加载,false就不加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        
        // 不显示授权回调地址(只有点击取消或授权时才会调用授权回调地址)
        if !urlString.hasPrefix(KBNetWorkTool.sharedInstance.redirect_uri) {
            return true
        }
        
        // 如果是授权回调地址,判断是点击取消还是授权(query是?后面的内容)
        if let query = request.URL?.query {
            //点击授权
            let codeString = "code="
            if query.hasPrefix(codeString) {
                //String->NSString,
                let queryNS = query as NSString
                let code = queryNS.substringFromIndex(codeString.characters.count)

                //截取code来获取accessToken
                loadAccessToken(code)
            } else {
                cancle() //点击取消
            }
        }
        
        return false
    }
    
    /// 截取code来获取accessToken
    private func loadAccessToken(code: String) {
        KBNetWorkTool.sharedInstance.loadAccessToken(code, finished: { (result, error) -> () in
            //判断网络是否请求错误
            if result == nil || error != nil {
                SVProgressHUD.showInfoWithStatus("你的网络不给力,请稍后尝试", maskType: SVProgressHUDMaskType.Black)
                //延迟1秒后关闭控制器
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    
                    self.cancle()
                })
                
                return
            }
            
            // 来到这里证明已经获取accessToken
            //1 字典转模型
            let userAccount = KBUserAccount(dict: result!)
            //2 保存到沙盒
            userAccount.saveUserAccount()
            //3 切换到welcomeController
            AppDelegate.switchRootViewController(false)
            //4
            self.cancle()
        })
    }
    
    /// webView加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}

